﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;

namespace MyPetHub.Filters
{
    public class AdminAuthorizationFilter : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //绕过带有AllowAnonymousAttribute特性的action
            var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
            if (allowAnonymous)
                return;

            if (context.HttpContext.Session.GetString("SysUser") == null)
            {
                string path = context.HttpContext.Request.Path.ToString();
                context.HttpContext.Response.Redirect("/Admin/AdminHome/Login?returnUrl=" + path);

                //设置短路，请求不再执行
                context.Result = new ObjectResult("login please");
                return;
            }
        }
    }
}
